package demo.spring.framework.context;

import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 用于获取ApplicationContext
 * 
 * @author hanjy
 *
 */
@Component
public class ApplicationContextAwareDemo implements ApplicationContextAware {

    private ApplicationContext context;

    public ApplicationContext getApplicationContext() {
        return context;
    }

    /**
     * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public <T> Map<String, T> getBeansOfType(Class<T> type) {
        return context.getBeansOfType(type);
    }

    public <T> T getBeanType(Class<T> type) {
        return context.getBean(type);
    }

    @SuppressWarnings("unchecked")
    public <T> T getBeanType(String beanName) {
        return (T) context.getBean(beanName);
    }

}